#include "tim.h"

char cycle = 100;

char duty_1_current = 0;
bit duty_1_polarity = 0;

char duty_2_current = 0;
bit duty_2_polarity = 0;

char duty_3_current = 0;
bit duty_3_polarity = 0;

char duty_target[3] = {30, 30, 30};
char duty_polarity[3] = {1, 1, 1};

void Timer0_Init(void)		//10微秒@33.1776MHz
{
	AUXR |= 0x80;			//定时器时钟1T模式
	TMOD &= 0xF0;			//设置定时器模式
	TL0 = 0xB4;				//设置定时初始值
	TH0 = 0xFE;				//设置定时初始值
	TF0 = 0;				//清除TF0标志
	TR0 = 1;				//定时器0开始计时
}

void Timer1_Init(void)		//1毫秒@33.1776MHz
{
	AUXR |= 0x40;			//定时器时钟1T模式
	TMOD &= 0x0F;			//设置定时器模式
	TL1 = 0x66;				//设置定时初始值
	TH1 = 0x7E;				//设置定时初始值
	TF1 = 0;				//清除TF1标志
	TR1 = 1;				//定时器1开始计时
	ET1 = 1;
}

void Timer_Init(void)
{
	Timer0_Init();
	Timer1_Init();

	duty_1_current = 0;
	duty_2_current = 0;
	duty_3_current = 0;

	ET0 = 1;				//使能定时器0中断
	ET1 = 1;
}

void Timer0_Isr(void) interrupt 1
{
	duty_1_current++;
	duty_2_current++;
	duty_3_current++;

	if (duty_1_current == cycle) {
		duty_1_current = 0;
	}

	if (duty_2_current == cycle) {
		duty_2_current = 0;
	}

	if (duty_3_current == cycle) {
		duty_3_current = 0;
	}

	duty_1_polarity = duty_polarity[0] & 0x01;
	duty_2_polarity = duty_polarity[1] & 0x01;
	duty_3_polarity = duty_polarity[2] & 0x01;

	if (duty_1_current == duty_target[0]) {
		M1A = ~duty_1_polarity;
	} else if (duty_1_current == 0) {
		M1A = duty_1_polarity;
		M1B = ~duty_1_polarity;
	}

	if (duty_2_current == duty_target[1]) {
		M2A = ~duty_2_polarity;
	} else if (duty_2_current == 0) {
		M2A = duty_2_polarity;
		M2B = ~duty_2_polarity;
	}

	if (duty_3_current == duty_target[2]) {
		LED = ~duty_3_polarity;
	} else if (duty_3_current == 0) {
		LED = duty_3_polarity;
	}
}

void TM1_Isr() interrupt 3
{
	task1++;
	task2++;
	if(uart1_Idle & 0x80){
		uart1_Idle++;
		if(uart1_Idle >= 0x85){
			rx1_buf[rx1_sta] = '\0';
			rx1_sta |= 0x80;
			uart1_Idle = 0;
		}
	}
}

